﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace flying_fish
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
            //取得程序当前所在路径，这点很重要
            string appPath = System.Windows.Forms.Application.StartupPath;
            //仅当图片存在时才加载图片
            if (System.IO.File.Exists(appPath + @"\pku.jpeg")) //图片需跟exe同一路径下
            {
                Image img = Image.FromFile(appPath + @"\pku.jpeg");
                this.pictureBox.Image = img;
            }
        }

        private void comboBox_serialport_SelectedIndexChanged(object sender, EventArgs e)
        {
            serialPort.PortName = comboBox_serialport.Text;
        }

        private void comboBox_serialport_Click(object sender, EventArgs e)
        {
            comboBox_serialport.Items.Clear();
            comboBox_Port_Update();
        }

        private void comboBox_Port_Update()
        {
            comboBox_serialport.Items.Clear();
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    comboBox_serialport.Items.Add(sValue);
                }
            }
        }

        private void system_startup_Click(object sender, EventArgs e)
        {
            if (!serialPort.IsOpen)
            {
                if (comboBox_serialport.Text != "")
                    try
                    {
                        serialPort.Open();
                    }
                    catch
                    {
                        MessageBox.Show("串口" + serialPort.PortName + "打开失败！");
                        return;
                    }
                else
                {
                    MessageBox.Show("请选择串口");
                    return;
                }
            }
            else
            {
                MessageBox.Show("串口已打开，请检查串口占用");
                return;
            }

            comboBox_serialport.Enabled = false;
            system_startup.Enabled = false;
            button_serialclose.Enabled = true;
            MessageBox.Show("启动成功");
            Task.Factory.StartNew(new Action(() =>
            {
                receivemsg();   //循环接收函数
            }));
        }

        private void receivemsg()
        {
            int receive_length = 0;
            byte[] receive_data = new byte[60];
            while (true)
            {
                try
                {
                    receive_length = serialPort.Read(receive_data, 0, serialPort.BytesToRead);//读取的字节数
                    Thread.Sleep(5);//延迟5ms

                    //data_decode(receive_data, receive_length);////调用数据解析函数
                    for (int k = 0; k < receive_length; k++)
                        richTextBox_receive.AppendText(receive_data[k].ToString("X2") + " ");
                    if(receive_length != 0)
                        richTextBox_receive.AppendText("\r\n");
                    Thread.Sleep(5);//延迟5ms

                    receive_data.Initialize();//初始化接收数据
                    receive_length = 0;//初始化字节长度

                    //update_data_delegate update = new update_data_delegate(update_data);//调用主线程委托，将解算出来的数据显示在主界面
                    //Invoke(update);

                }
                catch
                {

                }
            }
        }

        public string send_data = "CM0,0,0,NE\r\n";
        public static int frequency;
        public static int angle;
        public static bool SDcard;

        private void get_num()
        {
            try 
            {
                frequency = Convert.ToInt32(textBox_frequency.Text);
            }
            catch
            {

            }
            try
            {
                angle = Convert.ToInt32(textBox_degree.Text);
            }
            catch
            {

            }
            
            SDcard = checkBox_SDcard.Checked;
        }

        private void set_cmd()
        {            
            if(angle > 99 || angle < 0)
            {
                MessageBox.Show("ERROR: 角度超出界限");
                return;
            }

            if (frequency > 17 || frequency < 0)
            {
                MessageBox.Show("ERROR: 频率超出界限");
                return;
            }

            send_data = "CM" + angle.ToString() + ',' + (- angle).ToString() + ',' + (frequency * 10).ToString() + ',' + (SDcard == true ? 'Y' : 'N') + "E\r\n";
        }

        private void set_and_send_data()
        {
            get_num();
            set_cmd();
            serialPort.Write(send_data.ToCharArray(), 0, send_data.Length);
            richTextBox_send.AppendText(send_data);
        }

        private void button_set_Click(object sender, EventArgs e)
        {
            set_and_send_data();
        }

        private void button_open_Click(object sender, EventArgs e)
        {
            textBox_degree.Text = "95";
            set_and_send_data();
        }

        private void button_close_Click(object sender, EventArgs e)
        {
            textBox_degree.Text = "0";
            set_and_send_data();
        }

        private void button_stop_Click(object sender, EventArgs e)
        {
            textBox_degree.Text = "0";
            textBox_frequency.Text = "0";
            set_and_send_data();
        }

        private void button_slow_open_Click(object sender, EventArgs e)
        {
            get_num();
            int init_angle = angle;
            for (int k = 0, num = 50; k < num; k++)
            {
                float step = (95f - init_angle) / num;
                textBox_degree.Text = ((int)(init_angle + (k + 1) * step)).ToString();
                set_and_send_data();
                Thread.Sleep(1000 / num);
            }
        }

        private void button_serialclose_Click(object sender, EventArgs e)
        {
            comboBox_serialport.Enabled = true;
            system_startup.Enabled = true;
            serialPort.Close();
        }

        private void button_clear_Click(object sender, EventArgs e)
        {
            if((Button)sender == button_clear1)
                richTextBox_send.Clear();
            else if((Button)sender == button_clear2)
                richTextBox_receive.Clear();
        }

        private void button_save_Click(object sender, EventArgs e)
        {
            data.save_data_dialog((Button)sender == button_save1 ? 
                richTextBox_send : richTextBox_receive);
        }
    }
}
